#include"my_stdio.h"
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>

MyFile* BuyFile(int fd,int flag)
{
    MyFile* fp = (MyFile*)malloc(sizeof(MyFile));
    if(fp == NULL) return NULL;
    fp->fileno = fd;
    fp->flag = flag;
    fp->flush_method = LINE_FLUSH;
    memset(fp->outbuffer,0,sizeof(fp->outbuffer));
    fp->bufferlen = 0;
    return fp;
}

MyFile* MyFopen(const char* path,const char* mode)
{
    int fd = -1;
    int flag = 0;
    if(strcmp(mode,"w") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_TRUNC;
        fd = open(path,flag,0666);
    }
    else if(strcmp(mode,"a") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_APPEND;
        fd = open(path,flag,0666);
    }
    else if(strcmp(mode,"r"))
    {
        flag = O_RDONLY;
        fd = open(path,flag);
    }
    else 
    {}
    if(fd < 0) return NULL;
    return BuyFile(fd,flag);
}

void MyFclose(MyFile* file)
{
   if(file->fileno < 0) return;
   MyFflush(file);
   // 文件关闭要将缓冲区刷新
   close(file->fileno);
   free(file);
}

int MyFwrite(MyFile* file,void* str,int len)
{
    // 1. 拷贝
    memcpy(file->outbuffer + file->bufferlen,str,len);
    file->bufferlen += len;
    // 2. 判断是否满足刷新条件
    if((file->flush_method & LINE_FLUSH) && file->outbuffer[file->bufferlen - 1] == '\n')
        MyFflush(file);
    return 0;
}

void MyFflush(MyFile* file)
{
    if(file->bufferlen <= 0) return;
    // 将内容写进文件内核缓冲区
    write(file->fileno,file->outbuffer,file->bufferlen);
    // 将内容直接写入硬件
    fsync(file->fileno);
    file->bufferlen = 0;
}
